package com.wing.department.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.wing.auth.service.AuthService;
import com.wing.common.utils.JsonResult;
import com.wing.redis.utils.redis.RedisHelperImpl;
import com.wing.set.entity.ChanjetSet;
import com.wing.set.service.ChanjetSetService;
import com.wing.util.ConstantsUtil;
import com.wing.util.HttpsUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 仓库管理
 */
@Service
@Slf4j
public class DepartmentServiceImpl implements DepartmentService {

    @Resource
    RedisHelperImpl redisHelper;

    @Resource
    AuthService authService;

    @Resource
    ChanjetSetService chanjetSetService;

    @Override
    public JSONArray getDepartmentList() {

        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
         headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> param = new HashMap<>();
        HashMap resultMap= new HashMap<>();
        resultMap.put("SelectFields","ID,Code,Name,Parent.Code,Parent.Name");
        param.put("dto", resultMap);

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.DEPARTMENT_QUERY, headers, JSON.toJSONString(param));
        // 将字符串解析为JSONArray
        JSONArray objects = JSON.parseArray(result);

        return objects;
    }

    @Override
    public JsonResult createDepartment() {

        ChanjetSet chanjetSet = chanjetSetService.getById(1L);

        Map<String, String> headers = new HashMap<>();
        headers.put("appKey", chanjetSet.getAppKey());
        headers.put("appSecret", chanjetSet.getAppSecret());
        if(redisHelper.getValue("chanjetToken") == null){
            authService.getToken();
        }
        headers.put("openToken", redisHelper.getValue("chanjetToken").toString());

        Map<String, Object> param = new HashMap<>();
        Map<String, Object> deptParamObj = new HashMap<>();

        deptParamObj.put("Code", "coo1");
        deptParamObj.put("Name", "开发部");


        param.put("dto", deptParamObj);

        String result = HttpsUtils.httpsPostByJson(ConstantsUtil.CREATE_DEPARTMENT, headers, JSON.toJSONString(param));
        System.out.println(result);

        return JsonResult.success(result);
    }
}
